package shiyan6;

public class YiXinZhiShop {

    private static final int CAPACITY = 10;

    private final Bread[] breads = new Bread[CAPACITY];
    private int count = 0;
    private int putIndex = 0;
    private int takeIndex = 0;

    public synchronized void produceBread(Bread bread) {
        while (count == CAPACITY) {
            try {
                System.out.println(Thread.currentThread().getName() + " 容量已满，等待...");
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
        breads[putIndex] = bread;
        putIndex = (putIndex + 1) % CAPACITY;
        count++;
        System.out.println(Thread.currentThread().getName() + " 生产了面包 " + bread.getId() + "，当前数量：" + count);
        notifyAll();
    }

    public synchronized Bread consumeBread() {
        while (count == 0) {
            try {
                System.out.println(Thread.currentThread().getName() + " 没有面包，等待...");
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return null;
            }
        }
        Bread bread = breads[takeIndex];
        breads[takeIndex] = null;
        takeIndex = (takeIndex + 1) % CAPACITY;
        count--;
        System.out.println(Thread.currentThread().getName() + " 消费了面包 " + bread.getId() + "，当前数量：" + count);
        notifyAll();
        return bread;
    }
}
